import Vue from "vue";
import axios from "axios";
import { baseURL } from "./ip";
import store from "@/store";
const service = axios.create({
  baseURL,
  timeout: 5000
});

service.interceptors.request.use(
  config => {
    const token = localStorage.getItem("token");
    if (token) {
      // config.headers['Access-Token'] = token // 让每个请求携带自定义 token 请根据实际情况自行修改
      config.headers["Authorization"] = token; // 让每个请求携带自定义 token 请根据实际情况自行修改
    } else {
      delete config.headers["Authorization"];
    }
    return config;
  },
  error => {
    console.log(error);
    return Promise.reject();
  }
);

service.interceptors.response.use(
  response => {
    if (response.status === 200) {
      if (response.data.code === 9006 || response.data.code === 1001) {
        Vue.prototype.$message.error("登录失效");
        // 登录验证 9006登录失效，跳回登录页面
        store.commit("SET_ROLES", []);
        localStorage.removeItem("token");
        localStorage.removeItem("tags");
        setTimeout(() => {
          window.location.reload();
        }, 500);
      } else {
        return response.data;
      }
    } else {
      Promise.reject();
    }
  },
  error => {
    console.log(error);
    return Promise.reject();
  }
);

export default service;
